package com.dubbo.homework.filter;

import com.dubbo.homework.MethodPercentageManager;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

@Activate(group = CommonConstants.CONSUMER)
public class MonitorFilter implements Filter {

    private final MethodPercentageManager methodPercentageManager = MethodPercentageManager.create(60,5);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis();

        Result result = invoker.invoke(invocation);

        if (result.hasException() || RpcContext.getContext().isAsyncStarted()) {
            return result;
        }
        long endTime = System.currentTimeMillis();
        methodPercentageManager.increment(generateMehodName(invoker.getUrl(),invocation),endTime-startTime,endTime);
        return result;
    }

    private String generateMehodName(URL requestURL,Invocation invocation){
        StringBuilder sb = new StringBuilder();
        String path = requestURL.getPath();
        String method = invocation.getMethodName();
        sb.append(path).append(".").append(method).append("(");
        Class<?>[] parameterTypes = invocation.getParameterTypes();
        if(parameterTypes != null && parameterTypes.length > 0){
            for (int i = 0; i < parameterTypes.length; i++) {
                sb.append(parameterTypes[i].getSimpleName());
                if(i < parameterTypes.length-1){
                    sb.append(",");
                }
            }
        }
        sb.append(")");
        return sb.toString();
    }
}
